import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
var store = new Vuex.Store({
	state:{
		car:[]
	},
	mutations:{
		editSelected(state,id){
			state.car.forEach(item=>{
				if(item.id == id){
					item.selected = !item.selected;
				}
			})
		},
		initCarData(state,obj){
			console.log("==="+obj);
			state.car = obj;
		},
		editCount(state,obj){
			state.car.forEach(item=>{
				if(item.id == obj.id){
					item.count = obj.count;
				}
			});
		},
		deleteCar(state, id) {
		      // 根据Id，从store 中的购物车中删除对应的那条商品数据
		      state.car.some((item, i) => {
		        if (item.id == id) {
		          state.car.splice(i, 1)
		          return true;
		        }
		      })
		}
	},
	getters:{
		getAllCount(state){
			var count = 0;
			state.car.forEach(item=>{
				count += item.count;
			});
			return count;
		},
		getAllAmt(state){
			var amt = 0;
			state.car.forEach(item=>{
				amt += item.price * item.count;
			});
			return amt;
		},
		getSelected(state){
			var o = {}
			  state.car.forEach(item => {
				o[item.id] = item.selected
			  })
			  return o
		},
		getGoodsCountAndAmount(state) {
		      var o = {
		        count: 0, // 勾选的数量
		        amount: 0 // 勾选的总价
		      }
		      state.car.forEach(item => {
		        if (item.selected) {
		          o.count += item.count
		          o.amount += item.price * item.count
		        }
		      })
		      return o
		    }
	}
});

export default store;